<template>
    <page-wrap>
        <template #extension>
            <div class="cm-order-header">
                <div class="cm-order-header-info">
                    <div class="cm-order-header-left">
                        <span class="cm-order-header__label">服务员：</span>
                        <span class="cm-order-header__value cm-orange">{{cartStore.tableInfo.waiterUserName}}</span>
                    </div>
                    <div class="cm-order-header-right">
                        <div class="cm-order-header__text">{{dayjs().format('YYYY-MM-DD HH:mm:ss')}}</div>
                    </div>
                </div>
            </div>
        </template>
        <div class="orderConfirm-container">
            <div class="orderConfirm-main">
                <div class="orderConfirm-main-heading">
                    <div>当前商品信息</div>
                    <div class="select-item" @click="userShow = true" v-if="showYxOrder">
                        下单人：{{ pesronText }}
                        <div class="select-item-icon"></div>
                    </div>
                </div>
                <ul class="orderConfirm-main-list" v-if="showOrder">
                    <li class="cm-cart-cell confirm" v-for="v,index in cartStore.cartList" :key="index">
                        <div class="cm-cart-cell__cover" :style="{ backgroundImage: `url(${v.attachment})` }"></div>
                        <div class="cm-cart-cell__main">
                            <div class="cm-cart-cell__title">
                                <span class="cm-order-type-tag combo" v-if="v.type==2">套餐</span>
                                <span class="cm-order-type-tag single" v-if="v.type==0||v.type==1">单品</span>
                                <span class="cm-cart-cell__desc">{{v.goodsName}}</span>
                            </div>
                            <div class="cm-cart-cell__detail">{{v.flavor}}</div>
                            <div class="cm-cart-cell__footer">
                                <div class="cm-cart-cell__money">￥{{formatNumber(v.salePrice)}}</div>
                                <z-stepper disable-input :min="0" v-model="v.num" @plus="onHandleOrder('plus', v)" :step="v.saleLimitStep"
                                :max="v.saleLimitMax" @minus="onHandleOrder('minus', v)" :disabled="!showOrder" />
                            </div>
                        </div>
                        <!-- <van-checkbox v-model="v.checked" label-disabled shape="square"  @change="itemChange(index,$event)" v-if="!showOrder"></van-checkbox> -->
                        <!-- <van-radio name="1"  v-model="true" class="cm-cart-cell__check"></van-radio> -->
                    
                    </li>
                </ul>
                <ul class="orderConfirm-main-list" v-if="!showOrder">
                    <li class="cm-cart-cell confirm" v-for="v,index in toolArray" :key="index">
                        <div class="cm-cart-cell__cover" :style="{ backgroundImage: `url(${v.attachment})` }"></div>
                        <div class="cm-cart-cell__main">
                            <div class="cm-cart-cell__title">
                                <span class="cm-order-type-tag combo" v-if="v.type==2">套餐</span>
                                <span class="cm-order-type-tag single" v-if="v.type==0||v.type==1">单品</span>
                                <span class="cm-cart-cell__desc">{{v.goodsName}}</span>
                                <van-checkbox class="checkbox" v-model="v.checked" label-disabled shape="square" checked-color="#17171a" icon-size="16px"  @change="itemChange(index,$event)" v-if="!showOrder"></van-checkbox>
                            </div>
                            <div class="cm-cart-cell__detail">{{v.flavor}}</div>
                            <div class="cm-cart-cell__footer">
                                <div class="cm-cart-cell__money">￥{{formatNumber(v.salePrice)}}</div>
                                <div style="font-size: 16px;color: #FFFFFF;padding-right: 30px;">×{{ v.num }}</div>
                                <!-- <z-stepper disable-input :min="0" v-model="v.num" @plus="onHandleOrder('plus', v)" @minus="onHandleOrder('minus', v)" :disabled="!showOrder" /> -->
                            </div>
                            
                        </div>
                        
                        <!-- <van-radio name="1"  v-model="true" class="cm-cart-cell__check"></van-radio> -->
                    
                    </li>
                </ul>
                <div class="orderConfirm-main-heading remark">备注</div>
                <div class="orderConfirm-main-remark">
                    <van-field type="textarea" placeholder="请输入留言" v-model="postForm.remark" />
                </div>
            </div>
        </div>
        <template #footer>
            <div class="orderConfirm-footer">
                <div class="orderConfirm-footer-notify" v-if="isFirst && showLow>0">低消{{formatNumber(cartStore.tableInfo.consumeMinConsume)}}元，还差{{formatNumber(showLow)}}元。</div>
                <div class="orderConfirm-footer-panel">
                    <div class="orderConfirm-footer-info">
                        <div class="orderConfirm-footer__money">
                            <span class="orderConfirm-footer__subtotal">小计</span>
                            <span class="orderConfirm-footer__rmb">￥</span>
                            <span class="orderConfirm-footer__num">{{formatNumber(cartStore.totalAmount)}}</span>
                            <!-- <span class="orderConfirm-footer__num">&nbsp;&nbsp;会员价{{formatNumber(cartStore.totalVipAmount)}}</span> -->
                        </div>
                        <div class="orderConfirm-footer__quantity">共{{cartStore.totalCount}}件</div>
                    </div>
                    <div class="orderConfirm-footer-control">
                        <!-- <z-button bold @click="onConfirmCheckout" v-has-role="'waiter-checkout'" class="checkout">结账</z-button>
                        <z-button bold @click="onConfirmOrder" v-has-role="'waiter-order'" class="order" v-if="showOrder">下单</z-button> -->
                        <z-button bold @click="onConfirmOrder" v-has-role="'waiter-order'" class="order" v-if="showOrder" >下单</z-button>
                        <z-button bold @click="onConfirmCheckout" v-has-role="'waiter-checkout'" class="checkout">结账</z-button>
                    </div>
                </div>
            </div>
        </template>
    </page-wrap>
    <z-dialog v-model:show="payZero" @confirm="confirmPayZero" align="left" title="提示"
        content="商品金额为0，确认结账？"></z-dialog>

    <van-popup v-model:show="userShow" round position="bottom" >
        <div class="select-continar">
          <div class="flex-box-sub">
              <div class="close" @click="userShow = false">取消</div>
              <div class="title">选择下单人</div>
              <div class="submit" @click="onUserConfirm">确定</div>
          </div>
          <z-search
            placeholder="请输入下单人"
            v-model="inputInfo"
            @query="Onsearch"
            @update:model-value="onUpdateVal"
          ></z-search>
          <div class="person-box">
            <div class="person-item" @click="selectItem(index,item)" v-for="(item,index) in userColumns" :key="index"  :class="{ selected: item.selected }">
                  {{ item.label }}
            </div>
            <z-empty type="data" v-if="!userColumns.length" />
          </div>
        </div>
  </van-popup>

</template>
<script setup>
import useCartStore from '@/store/cart'
import dayjs from 'dayjs'
import { showToast } from 'vant';
import { formatNumber,calculateOrderQty } from '@/lib/util.js'
import Api from '@/api'
import ls from '@/lib/ls'
import _ from 'lodash'

const router = useRouter()
const route = useRoute()
const cartStore = useCartStore()
const showOrder = ref(false)
if(route.query.canOrder == '1'){
    showOrder.value = true
}
const showLow = computed(() => {
    if (cartStore.tableInfo.consumeMinConsume=='' || cartStore.tableInfo.consumeMinConsume==null) {
        return cartStore.tableInfo.minConsume - cartStore.totalAmount
    } else {
        return cartStore.tableInfo.consumeMinConsume - cartStore.totalAmount
    }
})

const isFirst = computed(() => {
    let output = true
    if (cartStore.tableInfo.currentConsume > 0) {
        output = false
    }
    return output
})

const postForm = reactive({
    consumeCode: cartStore.tableInfo.consumeCode || '',
    orderBatchCode:'',
    roomCode: cartStore.tableInfo.roomCode || '',
    remark: '',
    operType: '',
    detail: [],
})
const itemChange = (k,e)=>{
    // cartStore.cartList[k].checked = e
    toolArray.value[k].checked = e
    // console.log(cartStore.cartList[k].checked);
    console.log(toolArray.value[k].checked);
   
}

// 确认下单
const addFlag = ref(false)
const onConfirmOrder = function() {
    console.log(cartStore.totalAmount);
    
   
    addIndex()
    // 暂时低消不做限制
    // if (unref(isFirst) && unref(showLow) > 0) {
    //     showToast('低消未达到')
    //     return
    // }
    if(addFlag.value){
        showToast('加载中，请稍等')
        return
    }
    addFlag.value = true
    // if(ls.get('ORDER_BATCH_CODE')){
    //     postForm.orderBatchCode = ls.get('ORDER_BATCH_CODE')
    // }
    // 把购物车的数据处理成下单接口要的
    const arr = _.cloneDeep(cartStore.cartList)
    if(arr.length <= 0){
        showToast('购物车为空')
        return
    }
    const newArr = []
    arr.forEach((obj) => {
        if (obj.hasOwnProperty('detail')) {
            obj.detail.forEach((detail) => {
                const newDetail = { ...detail, type: '3' };
                newArr.push(newDetail);
            });
            delete obj.detail;
        }
        newArr.push(obj);
    });
    newArr.reverse()
    postForm.detail = newArr.map((obj,k) => {
        const { num, defaultQty, type, flavor, goodsPriceCode , stepNum,choiceType,isSelect,operType } = obj
        const convertedObj = {
            ...obj,
        };
        convertedObj.itemCode = ''
        convertedObj.doType = 'add'
    
        if (flavor==undefined) {
            convertedObj.flavor = ''
        }
        if (goodsPriceCode==undefined) {
            convertedObj.goodsPriceCode = ''
        }
        if (num !== undefined) {
            convertedObj.orderQty = num;
            delete convertedObj.num;
        }
        if (defaultQty !== undefined) {
            convertedObj.orderQty = defaultQty;
            delete convertedObj.defaultQty;
        }
        if (stepNum !== undefined) {
            convertedObj.orderQty = stepNum;
            delete convertedObj.stepNum;
        }
        if(choiceType == '1' && isSelect == false && operType == '0'){ // choiceType == '1' 是挑选种类  isSelect false 未选中 operType == '1'固定项目 不能修改配置
            convertedObj.orderQty = 0
            delete convertedObj.choiceType;
            delete convertedObj.isSelect;
        }
        if (type=='0'||type=='1') {
            convertedObj.itemType = '1'
        }
        if (type === '2') {
            convertedObj.flavor = ''
            convertedObj.itemType = '2'
            convertedObj.goodsPriceCode = convertedObj.goodsCode;
        }
        if (type === '3') {
            convertedObj.itemType = '3'
            convertedObj.goodsPriceCode = convertedObj.packageCode;
            delete convertedObj.packageCode;
        }

        delete convertedObj.mathType;
        delete convertedObj.type;
        delete convertedObj.attachment;
        delete convertedObj.orgCode;
        delete convertedObj.goodsFlavor;
        delete convertedObj.isEstmClear;
        delete convertedObj.mainAttachment;

        return convertedObj;
    });
    postForm.payType = '1'
    calculateOrderQty(postForm.detail)
    postForm.totalAmt = postForm.detail.reduce((sum, item) => sum + Number(item.salePrice), 0)

    postForm.marketUser = pesronCode.value
    postForm.marketUserName = pesronText.value
    Api.Common.AppObjProcess.Do({
        "functionName": "orderAdd",
        "contentData": postForm
    }).then(res => {
        cartStore.orderBatchCode = res.orderBatchCode
        ls.set('ORDER_BATCH_CODE',res.orderBatchCode)
        cartStore.goodsOrderStr = res.dataList.map(obj => obj.itemCode).join(',');
        console.log(cartStore.orderBatchCode);
        console.log(cartStore.goodsOrderStr);
        router.replace({
            path: '/open'
        })
        showToast('下单成功')
        addFlag.value = false
    }).catch(err=>{
        addFlag.value = false
    })
}
const payZero = ref(false)
const confirmPayZero = ()=>{
    onConfirmOrder()
}
// 确认结账
const onConfirmCheckout = ()=>{
    if(cartStore.totalAmount <= 0){
        payZero.value = true
        return
    }
    addIndex()
    // 暂时低消不做限制
    // if (unref(isFirst) && unref(showLow) > 0) {
    //     showToast('低消未达到')
    //     return
    // }
    // 把购物车的数据处理成下单接口要的
    const arr = _.cloneDeep(cartStore.cartList)
    if(arr.length <= 0){
        showToast('购物车为空')
        return
    }
    const newArr = []
    console.log(cartStore.cartList);
    arr.forEach((obj) => {
        if (obj.hasOwnProperty('detail')) {
            obj.detail.forEach((detail) => {
                const newDetail = { ...detail, type: '3' };
                newArr.push(newDetail);
            });
            delete obj.detail;
        }
        newArr.push(obj);
    });
    newArr.reverse()
    postForm.detail = newArr.map((obj,k) => {
        console.log(obj);
        
        const { num, defaultQty, type, flavor, goodsPriceCode,itemCode,stepNum,choiceType,isSelect,operType} = obj
        const convertedObj = {
            ...obj,
        };
        convertedObj.itemCode = ''
        convertedObj.doType = 'add'
    
        if (flavor==undefined) {
            convertedObj.flavor = ''
        }
        if (itemCode!=undefined) {
            convertedObj.itemCode = itemCode
        }
        if (goodsPriceCode==undefined) {
            convertedObj.goodsPriceCode = ''
        }
        if (num !== undefined) {
            convertedObj.orderQty = num;
            delete convertedObj.num;
        }
        if (defaultQty !== undefined) {
            convertedObj.orderQty = defaultQty;
            delete convertedObj.defaultQty;
        }
        if (stepNum !== undefined) {
            convertedObj.orderQty = stepNum;
            delete convertedObj.stepNum;
        }
        if(choiceType == '1' && isSelect == false && operType == '0'){ // choiceType == '1' 是挑选种类  isSelect false 未选中 operType == '1'固定项目 不能修改配置
            convertedObj.orderQty = 0
            delete convertedObj.choiceType;
            delete convertedObj.isSelect;
        }
        if (type=='0'||type=='1') {
            convertedObj.itemType = '1'
        }
        if (type === '2') {
            convertedObj.flavor = ''
            convertedObj.itemType = '2'
            convertedObj.goodsPriceCode = convertedObj.goodsCode;
        }
        if (type === '3') {
            convertedObj.itemType = '3'
            convertedObj.goodsPriceCode = convertedObj.packageCode;
            delete convertedObj.packageCode;
        }

        delete convertedObj.mathType;
        delete convertedObj.type;
        delete convertedObj.attachment;
        delete convertedObj.orgCode;
        delete convertedObj.goodsFlavor;
        delete convertedObj.isEstmClear;
        delete convertedObj.mainAttachment;

        return convertedObj;
    });
    if(route.query.canOrder != '1'){
        postForm.detail = postForm.detail.filter(item => item.checked)
    }
    ls.set('ORDER_FORM',postForm)
    ls.remove('ORDER_INFO')
    console.log(postForm);
   
    router.push({
        path: `/open/orderCashier`,
        query: {
            marketUser: pesronCode.value,
            marketUserName: pesronText.value
        }
    });
}

const onHandleOrder = (type, item) => {
    const product = {
        ...item,
        mathType: type
    }
    cartStore.RefreshCart(product)
}
const toolArray = ref([])
// 获取买单记录（已买单）
const getOrderDetail = () => {
    Api.Common.AppObjProcess.Do({
        "functionName": "GetOrderDetails",
        "contentData": {"consumeCode":cartStore.tableInfo.consumeCode,"pageIndex":"1","pageSize":"999"}
    }).then(res=>{
        console.log(res);
        
        cartStore.cartList = res.goodsList.filter(item=> {
                return item.itemType != '3';
        });
        cartStore.cartList.forEach(item => {
                item.num = item.orderQty
                item.checked = true
        });
        toolArray.value = cartStore.cartList
        ls.set('CART_LIST',cartStore.cartList)
        console.log(cartStore.cartList);
    })
}
// 商品添加index 
const addIndex = ()=>{
    cartStore.cartList.forEach((item,index)=>{
        item.indexStr = index
        if(item.type == '2'){
            item.detail.forEach((v,k)=>{
                v.indexStr = index
            })
        }
    })
}
watch(()=>toolArray.value,(nVal)=>{
    // 过滤出 checked 为 true 的元素
        console.log(nVal);
        const filteredCartList = toolArray.value.filter(item => item.checked);
        
        // 更新 cartStore.cartList
        cartStore.cartList = filteredCartList;
        ls.set('CART_LIST',cartStore.cartList)
},{ deep:true })



// ----------------------------------下单人操作 ----------------------------------
const showYxOrder = ref(false) // 显示下单人 已经下过单的和部分门店不需要
const userShow = ref(false)//下单人弹窗状态
const userColumns = ref([])  //下单人列表
const inputInfo = ref('')  //搜索输入的值
const pesronText = ref('') //下单人名字
const pesronCode = ref('') //下单人code
const Onsearch = () => {
    getWaiteretOrgGroup()
}
const searchTimer = ref(null)
const onUpdateVal = val => {
  clearTimeout(unref(searchTimer))
  searchTimer.value = setTimeout(() => {
    getWaiteretOrgGroup()
  }, 500)
}
// 获取下单人
const getWaiteretOrgGroup = ()=>{ // 确认营销人
    Api.Common.AppObjProcess.Do({
            functionName: 'GetOrgGroup',
            contentData: {"key":inputInfo.value}
          }).then(res => {
            userColumns.value = res.result
            console.log(res,'查询订台人列表')
          })
}
getWaiteretOrgGroup()

const selectItem = (index,v) => {
   // 取消所有项的选中状态
   userColumns.value.forEach(item => item.selected = false);
  // 选中当前点击的项
  userColumns.value[index].selected = true;
  console.log(v);
  
  pesronText.value = v.label
  pesronCode.value = v.value
};
const onUserConfirm = ()=>{ // 下单人确认
    if(pesronText.value == "") {
           showToast('请选择订台人')
       } else {
        userShow.value = false
       }
}




const onInit = ()=>{
    // 获取桌台购物车
    cartStore.GetTableCart()

    postForm.consumeCode = cartStore.tableInfo.consumeCode
    postForm.roomCode = cartStore.tableInfo.roomCode
    if(ls.get('ORDER_BATCH_CODE') && route.query.from == 'open'){ //点单后点结账
        getOrderDetail()
        ls.set('PAY_TYPE',2) // 1 第一次买单 2 点单后点结账
    }else{ // 完成一整个支付流程（不点挂单（点单））
        ls.set('PAY_TYPE',1) // 1 第一次买单
        if(ls.get('ORG_CODE') == '0024' || ls.get('ORG_CODE') == '0025' || ls.get('ORG_CODE') == '0014' ){ // 赤红门店需要
            showYxOrder.value = true
        }
    }
}
onInit()

</script>
<style scoped lang="scss">
::v-deep{
 .van-stepper__input{
    width: 50px;
 }
}

.orderConfirm-container {

    .orderConfirm-main {
        padding: 0 12px 12px;

        &-heading {
            font-size: 16px;
            font-family: PingFang SC;
            font-weight: bold;
            color: #FFFFFF;
            line-height: 16px;
            padding-top: 12px;

            &.remark {
                padding-top: 8px;
            }
        }

        &-list {
            .cm-order-type-tag {
                vertical-align: 1px;
            }
        }

        &-remark {
            padding-top: 12px;

            :deep(.van-cell) {
                background: #28282E;
                border-radius: 8px;
                padding: 7px 12px 12px 12px;
                height: 60px;

                .van-field__control {
                    font-size: 14px;
                    font-family: PingFang SC;
                    font-weight: 500;
                    color: #FFFFFF;
                    line-height: 24px;

                    &::placeholder {
                        color: #999999;
                    }
                }
            }
        }
        ::v-deep(.van-checkbox__icon--checked .van-icon ){
            color: #FFAA00 ;
            border: 1px solid #FFAA00 !important;
        }
    }
}
.cm-cart-cell__title{
    position: relative;
    .checkbox{
            position: absolute;
            right: 12px;
            top: 0;
        }
}
.orderConfirm-footer {

    &-notify {
        background: #663333;
        text-align: center;
        padding: 8px 0;
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #FFCCCC;
        line-height: 14px;
    }

    &-panel {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 12px;
    }

    &-info {}

    &__money {}

    &__subtotal {
        font-size: 12px;
        font-family: PingFang SC;
        font-weight: bold;
        color: #CCCCCC;
        line-height: 24px;
    }

    &__rmb {
        font-size: 12px;
        font-family: PingFang SC;
        font-weight: bold;
        color: #FFAA00;
        line-height: 24px;
    }

    &__num {
        font-size: 18px;
        font-family: PingFang SC;
        font-weight: bold;
        color: #FFAA00;
        line-height: 24px;
    }

    &__quantity {
        font-size: 12px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #CCCCCC;
        line-height: 12px;
        padding-top: 9px;
    }

    &-control {
        // width: 320px;
        display: flex;
        .checkout{
            width: 100px;
           
        }
        .order{
            width: 100px;
            margin-right: 10px;
            border-radius: 40px;
            background: #0c0c0d;
            border: 1px solid #CCBEA3;
            font-family: PingFang SC;
            font-weight: bold;
            font-size: 18px;
            color: #CCBEA3;
        }
    }
}
.orderConfirm-main-heading{
    display: flex;
    align-items: center;
    justify-content: space-between;
    .select-item {
    // width: 48%;
    position: relative;
    border: 1px solid #999999;
    border-radius: 4px;
    line-height: 14px;
    padding: 8px 0px 8px 11px;
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 500;
    color: #cccccc;
    padding-right: 30px;
    max-width: 70%;

    .select-item-icon {
      position: absolute;
      right: 12px;
      top: 13px;
      width: 11px;
      height: 6px;
      background-image: url('@/assets/svg/common/v_triangle_bottom_white.svg');
      background-repeat: no-repeat;
      background-position: center center;
      background-size: contain;
    }
  }
}
.select-continar {
  min-height: 300px;
  background: #45454d;
  .flex-box-sub {
    padding: 0 24px;
    display: flex;
    justify-content: space-between;
    height: 50px;
    line-height: 50px;
    .close {
      color: #999999;
       font-size: 16px;
    }
    .title {
      font-size: 20px;
      text-align: center;
      color: #fff;
    }
    .submit {
      font-size: 16px;
      color: #ea9d05;
    }
  }
  .person-box {
       height: 400px;
       padding-top: 20px;
       padding-bottom: 70px;
       overflow-y: auto;
       .person-item {
        text-align: center;
           font-size: 14px;
           color: #fff;
           margin-bottom: 25px;
       }
  }
  .person-item.selected {
      color:#ea9d05; /* 选中项的文字颜色 */
    }
}
</style>